package com.product.android.ui.widget;
import java.util.ArrayList;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.huewu.pla.lib.MultiColumnListView;
import com.huewu.pla.lib.internal.PLA_AbsListView;
import com.nd.android.u.allcommon.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.product.android.ui.adapter.BaseListViewAdapter;

/**
 * 分页加载瀑布流Listview
 * 
 * <br>
 * Created 2014-5-6 下午5:21:24
 * 
 * @version
 * @author chenqsh
 * 
 * @see
 */
public class PagingLoadListView extends MultiColumnListView {

	private String TAG = "PagingLoadListView";
//	private Context context = null;
	private PagingLoadFooterView loadingDialog = null;
	@SuppressWarnings({ "rawtypes" })
	private BaseListViewAdapter adapter = null;
	private int curTotalNumber;// 已装载进listview的数量
	private int curLastItemPos;// 当前页最后一个数据项的位置
	private int curPageNumber;// 当前页码
	private boolean bolCanLoadNextPage = true; // 是否可加载下一页
	private ProgressBar loadingProgressBar;
	private TextView loadingTv;
	private ImageView loadingFailIv;
	private int loadedNumber; // 该页加载数量

	public void cloneParam(PagingLoadListView listView){
		this.curTotalNumber = listView.curTotalNumber;
		this.curLastItemPos = listView.curLastItemPos;
		this.curPageNumber = listView.curPageNumber;
		this.bolCanLoadNextPage = listView.bolCanLoadNextPage;
		this.loadedNumber = listView.loadedNumber;
		this.loadingDialog.setVisibility(listView.loadingDialog.getVisibility());
		this.loadingProgressBar.setVisibility(listView.loadingProgressBar.getVisibility());
		this.loadingFailIv.setVisibility(listView.loadingFailIv.getVisibility());
		this.loadingTv.setVisibility(listView.loadingTv.getVisibility());
		this.loadingTv.setText(listView.loadingTv.getText());
	}
	public PagingLoadListView(Context context) {
		super(context);
//		this.context = context;
	}

	public PagingLoadListView(Context context, AttributeSet attr) {
		super(context, attr);
//		this.context = context;
		loadingDialog = new PagingLoadFooterView(context,R.layout.pagingload_footer);
		this.addFooterView(loadingDialog);
		loadingDialog.setVisibility(View.GONE);

		loadingProgressBar = (ProgressBar) loadingDialog
				.findViewById(R.id.footerpb);
		loadingTv = (TextView) loadingDialog.findViewById(R.id.footertv);
		loadingFailIv = (ImageView) loadingDialog.findViewById(R.id.nodataiv);
	}

	IListViewNextPageListener nextPageListener;

	public interface IListViewNextPageListener {
		/**
		 * 加载下一页数据
		 * 
		 * <br>
		 * Created 2014-5-7 下午4:54:29
		 * 
		 * @param page
		 * @author chenqsh
		 */
		public void onNextPage(int page);
	}

	private IScrollDirectionListener scrollDirectionListener;

	public interface IScrollDirectionListener {
		void onScrollUp();

		void onScrollDown();
	}

	/**
	 * 开始监听滚动事件
	 * 
	 * <br>
	 * Created 2014-5-14 下午3:25:52
	 * 
	 * @param listener
	 *            回调用于获取数据
	 * @param adapter
	 *            ListView的adapter
	 * @author chenqsh
	 */
	public void setOnScrollListener(IListViewNextPageListener listener,
			BaseListViewAdapter adapter) {
		this.nextPageListener = listener;
		this.adapter = adapter;
		setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScroll(PLA_AbsListView view, int mFirstVisibleItem,
					int mVisibleItemCount, int mTotalItemCount) {
				// 当LISTVIEW添加HEADERVIEW时 行数会增加 会导致判断错误 这边进行校正
				curLastItemPos = mFirstVisibleItem + mVisibleItemCount - 1
						- headerViewCount();
			}

			@Override
			public void onScrollStateChanged(PLA_AbsListView view,
					int scrollState) {
				// Log.e("xxx", "currentLastItemPosition:" + curLastItemPos
				// + " currentTotalNumber:" + curTotalNumber
				// + " currentPagePosition:" + curPageNumber
				// + " scrollState:" + scrollState);
				if (curLastItemPos >= (curTotalNumber - 1)
						&& (scrollState == OnScrollListener.SCROLL_STATE_TOUCH_SCROLL || scrollState == OnScrollListener.SCROLL_STATE_IDLE)) {
					// 当LISTVIEW添加HEADERVIEW时 行数会增加 会导致判断错误 这边进行校正
					setCurrentTotalNumber(view.getCount() - 1
							- headerViewCount());
					if (bolCanLoadNextPage
							&& view.getVisibility() == View.VISIBLE) {
						loadingDialog.setVisibility(View.VISIBLE);
						loadingProgressBar.setVisibility(View.VISIBLE);
						loadingTv.setVisibility(View.VISIBLE);
						loadingTv.setText(PagingConfig.LOADING_TXT);
						// 滚动加载时取数据
						bolCanLoadNextPage = false;
						asyncLoadNextPage();
					}
				}
			}
		});
	}

	/**
	 * fling滚动时暂停加载图片
	 * 
	 * <br>
	 * Created 2014-5-14 下午3:59:25
	 * 
	 * @param mImageLoader
	 * @param listener
	 * @param adapter
	 * @author chenqsh
	 */
	public void setPauseOnScrollListener(final ImageLoader imageLoader,
			IListViewNextPageListener listener, BaseListViewAdapter adapter) {
		this.nextPageListener = listener;
		this.adapter = adapter;
		setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScroll(PLA_AbsListView view, int mFirstVisibleItem,
					int mVisibleItemCount, int mTotalItemCount) {
				// 当LISTVIEW添加HEADERVIEW时 行数会增加 会导致判断错误 这边进行校正
				curLastItemPos = mFirstVisibleItem + mVisibleItemCount - 1
						- headerViewCount();
			}

			@Override
			public void onScrollStateChanged(PLA_AbsListView view,
					int scrollState) {
				switch (scrollState) {
				case OnScrollListener.SCROLL_STATE_IDLE:
					imageLoader.resume();
					break;
				case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
					break;
				case OnScrollListener.SCROLL_STATE_FLING:
					imageLoader.pause();
					break;
				}
				if (curLastItemPos >= (curTotalNumber - 1)
						&& (scrollState == OnScrollListener.SCROLL_STATE_TOUCH_SCROLL || scrollState == OnScrollListener.SCROLL_STATE_IDLE)) {
					// 当LISTVIEW添加HEADERVIEW时 行数会增加 会导致判断错误 这边进行校正
					setCurrentTotalNumber(view.getCount() - 1
							- headerViewCount());
					if (bolCanLoadNextPage
							&& view.getVisibility() == View.VISIBLE) {
						loadingDialog.setVisibility(View.VISIBLE);
						loadingProgressBar.setVisibility(View.VISIBLE);
						loadingTv.setVisibility(View.VISIBLE);
						loadingTv.setText(PagingConfig.LOADING_TXT);
						// 滚动加载时取数据
						bolCanLoadNextPage = false;
						asyncLoadNextPage();
					}
				}
			}
		});
	}

	public void setOnScrollDirectionListener(IScrollDirectionListener listener) {
		this.scrollDirectionListener = listener;
	}

	private float mLastMotionY;

	@Override
	public boolean onTouchEvent(MotionEvent event) {

		float y = event.getY();

		switch (event.getAction()) {
		case MotionEvent.ACTION_UP:

			if (mLastMotionY < y) {
				if (scrollDirectionListener != null) {
					scrollDirectionListener.onScrollUp();
				}
			} else if (mLastMotionY > y) {
				if (scrollDirectionListener != null) {
					scrollDirectionListener.onScrollDown();
				}
			}

			break;

		case MotionEvent.ACTION_DOWN:
			mLastMotionY = y;
			break;
		}
		return super.onTouchEvent(event);
	}

	/**
	 * 异步加载下一页数据
	 * 
	 * <br>
	 * Created 2014-5-7 下午4:52:05
	 * 
	 * @author chenqsh
	 */
	public void asyncLoadNextPage() {
		nextPageListener.onNextPage(curPageNumber + 1);
	}

	/**
	 * 设置当前页码
	 * 
	 * <br>
	 * Created 2014-5-14 下午3:26:46
	 * 
	 * @param currentPagePosition
	 * @author chenqsh
	 */
	public void setCurrentPageNumber(int currentPagePosition) {
		this.curPageNumber = currentPagePosition;
	}

	/**
	 * 设置当前listview显示的总数
	 * 
	 * <br>
	 * Created 2014-5-14 下午3:26:57
	 * 
	 * @param currentTotalNumber
	 * @author chenqsh
	 */
	public void setCurrentTotalNumber(int currentTotalNumber) {
		this.curTotalNumber = currentTotalNumber;
	}

	public int getCurrentTotalNumber() {
		return this.curTotalNumber;
	}

	/**
	 * 处理滚动数据加载成功的情况
	 * 
	 * <br>
	 * Created 2014-5-14 下午3:27:11
	 * 
	 * @author chenqsh
	 */
	public void handleSuccess() {
		// Log.i("xxx", "currentPagePosition  1-------:" + curPageNumber);
		bolCanLoadNextPage = true;
		if (loadedNumber < PagingConfig.PAGE_SIZE) { // 最后一页
			loadingDialog.setVisibility(View.VISIBLE);
			loadingProgressBar.setVisibility(View.GONE);
			loadingFailIv.setVisibility(View.GONE);
			if(curLastItemPos > 0){
				loadingTv.setVisibility(View.VISIBLE);
				loadingTv.setText(PagingConfig.LOADING_END_TXT);
			}
			bolCanLoadNextPage = false;
		} else {
			curPageNumber += 1;
			loadingDialog.setVisibility(View.GONE);
		}

	}

	public void handleData(ArrayList<?> list) {
		if (curTotalNumber == 0 && (list == null || list.size() == 0)) {
			handleFailure();
		}else{
			handleSuccessAndAddData(list);
		}
	}

	/**
	 * 在执行成功的时候，将数据添加到adapter里面
	 * 
	 * <br>
	 * Created 2014-5-14 下午3:27:26
	 * 
	 * @param list
	 * @author chenqsh
	 */
	public void handleSuccessAndAddData(ArrayList<?> list) {
		addNextPageDataList(list);
		handleSuccess();
	}

	/**
	 * 处理滚动数据加载失败的情况
	 * 
	 * <br>
	 * Created 2014-5-14 下午3:27:38
	 * 
	 * @author chenqsh
	 */
	public void handleFailure() {
		loadingDialog.setVisibility(View.VISIBLE);
		loadingProgressBar.setVisibility(View.GONE);
		loadingFailIv.setVisibility(View.VISIBLE);
		loadingTv.setVisibility(View.VISIBLE);
		loadingTv.setText(PagingConfig.LOAD_FAIL_TXT);
	}

	/**
	 * 往listview中新增数据
	 * 
	 * <br>
	 * Created 2014-5-14 下午3:27:48
	 * 
	 * @param newAdapter
	 * @author chenqsh
	 */
	public void setNewAdapter(BaseListViewAdapter newAdapter) {
		adapter = newAdapter;
		adapter.notifyDataSetChanged();
		curTotalNumber = adapter.getCount();
	}

	private void addNextPageDataList(ArrayList<?> list) {

		if (list != null && list.size() > 0) {
			loadedNumber = list.size();
			adapter.addItemList(list);
			curTotalNumber = adapter.getCount();
		} else {
			loadedNumber = 0;
		}
	}

	@Override
	public void setAdapter(ListAdapter adapter) {
		super.setAdapter(adapter);
		if (adapter != null) {
			curTotalNumber = adapter.getCount();
			this.adapter = (BaseListViewAdapter) adapter;
		}
	}

	/**
	 * 移除等待条
	 * 
	 * <br>
	 * Created 2014-5-14 下午3:28:01
	 * 
	 * @author chenqsh
	 */
	public void removeLoadingDialog() {
		loadingDialog.setVisibility(View.GONE);
	}

	/**
	 * 展现等待条
	 * 
	 * <br>
	 * Created 2014-5-14 下午3:28:09
	 * 
	 * @author chenqsh
	 */
	public void showLoadingDialog() {
		loadingDialog.setVisibility(View.VISIBLE);
	}

	private void removeFooterView() {
		if (this.getAdapter() != null) {
			if (hasFooterView()) {// totalPageNumber <= 1 &&
				this.removeFooterView(loadingDialog);
				adapter.notifyDataSetChanged();
			}
		}
	}

	private boolean hasFooterView() {
		if (this.getFooterViewsCount() == 1) {
			return true;
		}
		return false;
	}

	private int headerViewCount() {
		return this.getHeaderViewsCount();
	}

	/**
	 * 重置参数
	 * 
	 * <br>
	 * Created 2014-5-14 下午3:28:17
	 * 
	 * @author chenqsh
	 */
	public void resetParams() {
		// 取消状态view
		resetLoadingDialog();

		// 清空适配器
		if (adapter != null) {
			if (null != adapter.getDataList()) {
				adapter.getDataList().clear();
				adapter.mHRRecognizeSet.clear();
				setAdapter(adapter);
			}
		}

		// 清空分页信息
		bolCanLoadNextPage = true;
		curTotalNumber = 0;// 已装载进listview的数量
		curLastItemPos = 0;// 当前页最后一个数据项的位置
		curPageNumber = 0;// 当前页码
	}

	private void resetLoadingDialog() {
		loadingProgressBar.setVisibility(View.VISIBLE);
		loadingTv.setVisibility(View.GONE);

		if (this.getFooterViewsCount() == 0) {
			this.addFooterView(loadingDialog);
		}
		loadingDialog.setVisibility(View.GONE);
	}

	/**
	 * 分页加载参数配置
	 * 
	 * <br>
	 * Created 2014-5-14 下午3:28:32
	 * 
	 * @version PagingLoadListView
	 * @author chenqsh
	 * 
	 * @see
	 */
	public class PagingConfig {
		public static final int PAGE_SIZE = 20;
		
		public static final String LOADING_TXT = "正在加载...";
		public static final String LOADING_END_TXT = "到底了哦!";
		public static final String LOAD_FAIL_TXT = "暂无数据";
	}
}